//
//  Bullet.m
//  SpaceStorm
//
//  Created by 祥 雍 on 13-4-26.
//  Copyright (c) 2013年 __MyCompanyName__. All rights reserved.
//

#import "Bullet.h"

@implementation Bullet

@synthesize bulletId = _bulletId;
@synthesize view = _view;
@synthesize isActive = _isActive;
@synthesize isTeam = _isTeam;

+(id) bulletWithId:(int) bulletId
{
    return [[[self alloc] initWithId:bulletId] autorelease]; 
}

-(id) initWithId:(int) bulletId
{
    self = [super init]; 
	
	if (self!= nil) 
    {
        _bulletId = bulletId;
        //视图
        CCSprite* bulletBG = [CCSprite spriteWithSpriteFrameName:[NSString stringWithFormat:@"bullet%d.png", _bulletId]];
        self.texture = bulletBG.texture; 
        self.textureRect = bulletBG.textureRect;
        
//        self.view = [BulletView viewWithModelId:bulletId];
//        [self addChild:self.view];
    }
    
    return self;
}

/**
	发射子弹
	@param startPosition 起始位置
	@param velocity 带方向的速度
 */
-(void) shootBulletAt:(CGPoint)startPosition
             rotation:(float)rotation
                speed:(float)speed
                range:(float)range
           damageType:(int)damageType
          damageValue:(float)damageValue
{
    //设置激活状态
    _isActive = YES;
    
    //设置出发位置，并显示
    self.position = startPosition;
    self.visible = YES;
    
    //调整目标方向
    self.rotation = rotation;
    
    //启动移动
    float duratiopn = range / speed;
    CGPoint velocity = ccpForAngle(CC_DEGREES_TO_RADIANS(90 - rotation));
    CGPoint targetpoint = ccpAdd(startPosition, ccpMult(velocity, range));
    id ac1 = [CCMoveTo actionWithDuration:duratiopn position:targetpoint];
    id actionCallFunc = [CCCallFunc actionWithTarget:self selector:@selector(onFinishLife)];
    id sq = [CCSequence actions:ac1, actionCallFunc, nil];
    [sq setTag:88];
    [self runAction:sq]; 
}

/**
	子弹生命周期内没打到敌人，要自己冻结
 */
-(void) onFinishLife
{
    //设置激活状态
    _isActive = NO;
    
    //设置出发位置，并显示
    self.position = ccp(0, 0);
    self.visible = NO;
    
    //移除动作
    [self stopActionByTag:88];
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)
	
	// don't forget to call "super dealloc"
	[super dealloc];
}

@end
